//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

namespace TridentProvenanceService
{
    using System;
    using System.Diagnostics;
    using System.ServiceProcess;
    using Microsoft.Research.ProvenanceInterfaces;
    using Microsoft.Research.ProvenanceSubscriber;
    using Microsoft.Practices.Unity;
    using System.Globalization;
    using Microsoft.Practices.EnterpriseLibrary.Logging;


    public partial class ProvenanceSubscriberService : ServiceBase
    {
        internal string logCategory = "General";
        /// <summary>
        /// Unity container.
        /// </summary>
        private UnityContainer container;

        /// <summary>
        /// Provenance subscriber instance.
        /// </summary>
        private IProvenanceSubscriber provenanceSubScriber;

        public ProvenanceSubscriberService()
        {
            InitializeComponent();
            this.InitializeService();
        }

        private void InitializeService()
        {
            this.container = new UnityContainer();

            try
            {
                this.provenanceSubScriber = this.container.Resolve<ProvenancePublisher>();
            }
            catch (Exception ex)
            {
                Logger.Write(ex.Message, logCategory);
            }
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                Logger.Write("Starting provenance Service", logCategory);
                this.provenanceSubScriber.Start();
                Logger.Write("Started provenance Service", logCategory);
            }
            catch (Exception ex)
            {
                Logger.Write(ex.Message, logCategory);
                this.Stop();
            }
        }

        protected override void OnStop()
        {
            try
            {
                Logger.Write("Stopping provenance Service", logCategory);
                this.provenanceSubScriber.Halt();
                Logger.Write("Provenance service stopped", logCategory);
            }
            catch (Exception ex)
            {
                Logger.Write(ex.Message, logCategory);
            }
        }
    }
}
